package ltd.hyangyang.rpc.core.serialize;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import ltd.hyangyang.rpc.common.bean.Request;
import ltd.hyangyang.rpc.common.bean.Response;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

//使用Kyro进行序列化
public class KryoSerialize {


    public static <T> T deserialize(byte[] bytes,Class<T> classType){
        //解码
        Kryo kryo = initKryo();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Input input = new Input(byteArrayInputStream);
        Object object = null;
        try {
            object = kryo.readObject(input,classType);
        }catch (Exception e){
            e.printStackTrace();
        }


        return (T) object;
    }

    static Kryo initKryo(){
        Kryo kryo = new Kryo();
        kryo.register(Request.class);
        kryo.register(Response.class);
        return kryo;
    }

    public static byte[] serialize(Object object){
        Kryo kryo = initKryo();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Output output = new Output(byteArrayOutputStream);
        kryo.writeObject(output,object);
        byte[] bytes = output.getBuffer();

        return bytes;
    }
}
